package com.dyh.quickdemozwei.mians;

import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
public class YtqQueue<E> {

    private final ReentrantLock listAccessLock = new ReentrantLock();
    private final int maxSize;
    private final Condition full = listAccessLock.newCondition();
    private final Condition empty = listAccessLock.newCondition();
    private final LinkedList<E> datas = new LinkedList<>();

    public YtqQueue(int maxSize) {
        this.maxSize = maxSize;
    }

    public void addTail(E e){
        listAccessLock.lock();
        try{
            if (datas.size()==maxSize){
                full.await();
            }

            datas.add(e);
            empty.signal();
        }
        catch (Exception ex){
            log.error("异常ex=",ex);
        }
        finally {
            listAccessLock.unlock();
        }
    }

    public void removeHead(){
        listAccessLock.lock();
        try{
            if (datas.size()==0){
                empty.await();
            }
            datas.removeFirst();
            full.signal();
        }
        catch (Exception ex){
            log.error("异常ex=",ex);
        }
        finally {
            listAccessLock.unlock();
        }
    }

//    public static void main(String[] args) throws InterruptedException {
//
//        YtqQueue<Byte> queue = new YtqQueue<>(2);
//
//        for (int i = 0;i<5;i++){
//            new Thread(()->{
//                log.info("{} 开始入队列",Thread.currentThread().getName());
//                queue.addTail((byte)1);
//                log.info("{} 成功入队列",Thread.currentThread().getName());
//
//            }).start();
//        }
//
//        for (int i = 0;i<5;i++){
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
//            new Thread(()->{
//
//                log.info("{} 开始出队列",Thread.currentThread().getName());
//                queue.removeHead();
//                log.info("{} 成功出队列",Thread.currentThread().getName());
//
//            }).start();
//        }
//
//        Thread.sleep(100000);
//    }

    interface Itf{
        abstract void xxx();
    }

    public static void main(String[] args) {
        String str = "https://img14.360buyimg.com/imgzone/jfs/t1/94840/17/36383/2851/642672eaF05ccd329/2be6eb22bde2d790.png";

        if (str.startsWith("https://img14.360buyimg.com/imgzone/")){
            str = str.replace("https://img14.360buyimg.com/imgzone/","");
        }

        System.out.println();
    }

}
